# -*- coding: utf-8 -*-
# filename: airfaretrend.py

from urllib import urlopen
from json import loads
from datetime import datetime, timedelta
from time import sleep

def getAWeekPrice(dep, arr, mDateStr):
    uc = urlopen("https://lp.flight.qunar.com/api/lp_calendar"
                 "?dep={dep}&arr={arr}&dep_date={depdate}"
                 "&adultCount=1&month_lp=0&tax_incl=0&direct=0"
                 "&callback=jsonp_1osfwzsv3g15m4c"
                 .format(dep=dep, arr=arr, depdate=mDateStr)
                 )
    content = uc.read()
    uc.close()
    # print content
    if '' == content:
        print "Can't get json file!"
        return -1
    else:
        banner = '[' + content.split('[')[1][:-3]
        # print banner
        jsonp = loads(banner)
        # print jsonp
        pl = []
        for js in jsonp:
            # print js['price']
            pl.append(js['price'])
        return pl

def getPriceList(dep, arr, today, priceAmnt):
    priceList = []
    middleDay = today + timedelta(days=3,)
    # middleDate = datetime.date(middleDay)
    # print middleDate
    mDateStr = middleDay.strftime("%Y-%m-%d")
    priceList.extend(getAWeekPrice(dep, arr, mDateStr))
    cnt = 0
    loopTimes = int((priceAmnt-3) / 7)
    while cnt < loopTimes:
        middleDay = middleDay + timedelta(days=7, )
        # middleDate = datetime.date(middleDay)
        mDateStr = middleDay.strftime("%Y-%m-%d")
        priceList.extend(getAWeekPrice(dep, arr, mDateStr))
        cnt += 1
    # print priceList
    return priceList

def saveZBPrice(getPriceAmount):
    today = datetime.now()
    print 'START>>>', today
    todayStr = today.strftime("%Y-%m-%d")
    # print 'Get prices...'
    zbpl = getPriceList('珠海', '北京', today, getPriceAmount)
    # print 'Write file...'
    with open("ZH-BJ.txt", 'ab') as fs:
        fs.write(todayStr + ' ' + str(zbpl) + '\r\n')
    # print 'Get prices...'
    bzpl = getPriceList('北京', '珠海', today, getPriceAmount)
    # print 'Write file...'
    with open("BJ-ZH.txt", 'ab') as fs:
        fs.write(todayStr + ' ' + str(bzpl) + '\r\n')
    print '>>END>>>', datetime.now()

if __name__ == '__main__':
    GET_PRICE_AMOUNT = 50
    while True:
        saveZBPrice(GET_PRICE_AMOUNT)
        sleep(28800)    # 8 hours

